#!/usr/bin/env python

from core.ide.themesmanager import ThemesManager
from core.ide.datamangager import *
from core.ide.langsmanager import LangsManager
import fnmatch
import xml.etree.ElementTree as ET

        
class LocalObject:
    def __init__(self,path):
        self.path=os.path.abspath(path)
        self.path=self.path.replace("\\","/")
        self.name=os.path.basename(self.path)
        self.parent=None
        #self.data=None
        self.item=None
        self.project=None
        
    def setName(self,name):
        if os.path.exists(self.path):
            os.rename(self.path,name)
        self.name=name
        self.path=os.path.dirname(self.path)+"/"+self.name
        return True
        
        
    def getPath(self):
        if self.parent:
            return self.parent.getPath()+"/"+self.name
        else:
            return self.name
        
    def moveTo(self,dir_):
        if isinstance(dir_,Directory):
            shutil.move(self.path,dir_.path)
            return True
        return False
        
class File(LocalObject):
    
    NORMAL_ROOT=0
    DOCUMENT_ROOT=1
    SUB_DOCUMENT=2
    
    
    def __init__(self,path,name=None):
        self.type="file"
        LocalObject.__init__(self,path)
        #self.path=os.path.abspath(path)
        #self.path=self.path.replace("\\","/")
        #self.name=os.path.basename(self.path)
        self.ext=os.path.splitext(path)[1][1:]
        
        self._status=0
        
    def icon(self):
        id_=ThemesManager().getDefaultTheme().getWxIdImage("file_16",'file_'+self.ext)
        if not id_:
            id_=ThemesManager().getDefaultTheme().getWxIdImage("file_16",'file')
        
        return id_
        #return

    def setStatus(self,status):
        self._status=status
        

    def getStatus(self):
        return self._status

    
    def getProject(self):
        if not self.project:
            self.project=self.getRoot()
        return self.project
    
    def getRoot(self):
        if self.parent:
            return self.parent.getRoot()
        else:
            return self




class Directory(LocalObject):
    OPEN=1
    CLOSE=0
    def __init__(self,path,name=None):
        self.type="dir"
        LocalObject.__init__(self,path)
        self._created=False
        self.suffix=""
        self.state=0
    
    def setState(self,state):
        self.state=state
    
    def moveTo(self,file_):
        pass
    
    def setSuffix(self,suffix):
        if suffix and len(suffix):
            self.suffix="_"+suffix
        else:
            self.suffix=""
    
    def read(self):
        patterns=DataMangager().getData('Project','Exclude filters',"*.pyc,*.pyo,.*",None,'File').value.split(",")
        patterns.append(self.getProject().file)
        self._created=True
        self._dirs=[]
        self._files=[]
        
        self._listdir = os.listdir(self.path)
        for path in self._listdir:
            if any(fnmatch.fnmatch(path, p) for p in patterns):
                continue
            path=self.path+'/'+path
            if(os.path.isdir(path)):
                self._dirs.append(Directory(path))
            else:
                self._files.append(File(path))
        #self._dirs.sort()
        #self._files.sort()
        
    def icon(self):
        if self.state==0:
            return ThemesManager().getDefaultTheme().getWxIdImage("file_16",'folder'+self.suffix)
        else:
            return ThemesManager().getDefaultTheme().getWxIdImage("file_16",'folder_open'+self.suffix)

    
    def getChildName(self,name):
        if not self._created:
            return None
        l=self.getContent()
        for f in l:
            if f.name==name:
                return f
        return None
    
    def getContent(self):
        ret=self._dirs+self._files
        return ret
    
    def getContentDir(self):
        return self._dirs
    
    def getContentFile(self):
        return self._files
    
    def isModified(self):
        return self._listdir!=os.listdir(self.path)
        
    
    def getProject(self):
        if not self.project:
            self.project=self.getRoot()
        return self.project
       
    def getRoot(self):
        if self.parent:
            return self.parent.getRoot()
        else:
            return self
        
        
class Project (Directory):
    def __init__(self,file_):
        self.doc=None
        self.type=None
        self.path=file_.replace("\\","/")
        
        ext=os.path.splitext(file_)[1]
        self.name=os.path.splitext(os.path.basename(file_))[0]
        
        if os.path.exists(file_):
            if ext==".xml" or ext==".druidxprj":
                f=open(file_,"r")
                self.readXml(f.read())
                f.close()
            else:
                self.readZip(file_)
           
        self.file=file_
        
        Directory.__init__(self,self.getBaseDir(),self.name)
        
    def readZip(self,zip_):
        pass
    
    def readXml(self,xml_):
        self.doc=ET.fromstring(xml_)

        self._basedir=os.path.normpath(os.path.join(os.path.dirname(self.path),self.doc.find('head/dir').text)).replace("\\","/")
        self.setDocumentRoot(self.doc.find('head/document_root').text)
        self.data=DataObject()
        self.data.readData(self.doc.find("data"))
        
    def getBaseDir(self):
        return self._basedir

    def getDocumentRoot(self):
        return self._documentRoot
        
    def setDocumentRoot(self,path):
        if not path:
            self._documentRoot=""
        else:
            self._documentRoot=self.cleanPath(path)
            self.doc.find('head/document_root').text=self._documentRoot
    
    def cleanPath(self,path):
        
        base=os.path.abspath(self.getBaseDir()).replace('\\',"/")
        if os.path.exists(base+"/"+path):
            return path
        path=os.path.normpath(os.path.join(self.getBaseDir(), path)).replace('\\',"/")
        path=path.replace(base,"").replace('\\',"/")[1:]
        if path[0]=="/":
            path=path[1:]
        return path
    
    def getProjectType(self):
        return self.type or LangsManager().getLangFromFile(self.getDocumentRoot())
    
    def getDataObject(self):
        return self.data
       
    def getRoot(self):
        return self
    
    def save(self):
        xml='<?xml version="1.0" encoding="UTF-8"?>'
        xml+="\n<project>"
        xml+="\n\t<head>"
        xml+="\n\t<dir>./</dir>"
        xml+="\n\t<document_root>"+self._documentRoot+"</document_root>"
        xml+="\n\t</head>"
        xml+="\n"+self.data.getStringXml(1)
        xml+="\n</project>"
        f=open(self.file,'w')
        f.write(xml)
        f.close()